package twitter;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;

import javax.xml.parsers.ParserConfigurationException;

import org.xml.sax.SAXException;

public class UserInformationFetcher {
	Client client;
	public UserInformationFetcher(Client client) {
		this.client = client;
	}
	
	public String fetch() {
		String urlString = null;
		if(client.user.id != null) {
			urlString = "http://api.twitter.com/1/users/show.xml?user_id="+ client.user.id;
		}
		else { // if user id unknown > use screenname instead
			urlString = "http://api.twitter.com/1/users/show.xml?screen_name="+ client.user.screenName;
		}
		
		try {
			URL url = new URL(urlString);
			Downloader downloader = new Downloader(url);
			String xml = downloader.fetchAsString();
			if(xml != null) {
				if(xml.endsWith("_blocked")) {
					client.clientWasBlocked();
					return "blocked";
				}
				else if(xml.endsWith("_protected")) {
					return "protected";
				}
				else if(xml.startsWith("_exeption")) {
					return "exception";
				}
				else if(!xml.startsWith("_exeption")) {
					HashMap<String, String> userData = parse(xml);
					if(userData != null) {
						client.handleUserDataResults(userData);
						return null;
					}
				}
			}
			else {
				return "error";
			}

		} catch (MalformedURLException e) {
			e.printStackTrace();
		}
		return "error";
	}
	
	private HashMap<String, String> parse(String string) {		
		HashMap<String, String> data = new HashMap<String, String>();

		try {
			CustomXpath cx = new CustomXpath(string);
			
			// Return null if something going wrong like: user not found
			if(cx.getFirstTextContent("/hash/error/text()") != null) {
				System.err.println("Some thing going wrong while loading user informations");
				return null;
			}
			
			String id	 		= cx.getFirstTextContent("/user/id/text()");
			String name 		= cx.getFirstTextContent("/user/name/text()");
			String screen_name 	= cx.getFirstTextContent("/user/screen_name/text()");
			String location 	= cx.getFirstTextContent("/user/location/text()");
			String description 	= cx.getFirstTextContent("/user/description/text()");
			String url 			= cx.getFirstTextContent("/user/url/text()");
			
			data.put("id", id);
			data.put("name", name);
			data.put("screen_name", screen_name);
			data.put("location", location);
			data.put("description", description);
			data.put("url", url);
			
			System.out.println(" + Fetched users information");
		} catch (ParserConfigurationException e) {
			e.printStackTrace();
		} catch (SAXException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		return data;
	}
}
